<template>
  <Sidebar :menu-items="menuItems" title="管理系统">
    <div class="flex-1 flex flex-col overflow-hidden">
      <!-- 顶部导航 -->
      <Header 
        :user-info="authStore.userInfo"
        :show-notification="true"
        :notification-count="5"
        @logout="handleLogout"
        @profile-click="handleProfileClick"
        @settings-click="handleSettingsClick"
      />
      
      <!-- 主内容区 -->
      <main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-50 p-6">
        <div class="max-w-7xl mx-auto">
          <!-- 页面标题 -->
          <div class="mb-8">
            <h1 class="text-2xl font-bold text-gray-900">管理首页</h1>
            <p class="mt-1 text-sm text-gray-600">
              欢迎回来，{{ authStore.userInfo?.name }}！今天是 {{ currentDate }}
            </p>
          </div>

          <!-- 统计卡片 -->
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <StatCard
              v-for="stat in statistics"
              :key="stat.title"
              :title="stat.title"
              :value="stat.value"
              :change="stat.change"
              :icon="stat.icon"
              :color="stat.color"
            />
          </div>

          <!-- 图表区域 -->
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <!-- 报到趋势图 -->
            <Card title="报到趋势" class="h-96">
              <DashboardChart
                type="line"
                :data="registrationTrendData"
                :loading="chartsLoading"
                height="300px"
              />
            </Card>

            <!-- 专业分布图 -->
            <Card title="专业分布" class="h-96">
              <DashboardChart
                type="pie"
                :data="majorDistributionData"
                :loading="chartsLoading"
                height="300px"
              />
            </Card>
          </div>

          <!-- 缴费进度和快捷操作 -->
          <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- 缴费进度图 -->
            <Card title="缴费进度" class="lg:col-span-2 h-80">
              <DashboardChart
                type="bar"
                :data="paymentProgressData"
                :loading="chartsLoading"
                height="240px"
              />
            </Card>

            <!-- 快捷操作 -->
            <Card title="快捷操作" class="h-80">
              <div class="space-y-3">
                <button
                  v-for="action in quickActions"
                  :key="action.name"
                  @click="handleQuickAction(action.path)"
                  class="w-full flex items-center p-3 text-left border border-gray-200 rounded-lg hover:bg-gray-50 hover:border-gray-300 transition-colors duration-200"
                >
                  <component :is="action.icon" class="h-5 w-5 text-gray-400 mr-3" />
                  <div>
                    <div class="text-sm font-medium text-gray-900">{{ action.name }}</div>
                    <div class="text-xs text-gray-500">{{ action.description }}</div>
                  </div>
                </button>
              </div>
            </Card>
          </div>

          <!-- 最新动态 -->
          <div class="mt-8">
            <Card title="最新动态">
              <div class="space-y-4">
                <div
                  v-for="activity in recentActivities"
                  :key="activity.id"
                  class="flex items-start space-x-3 p-3 hover:bg-gray-50 rounded-lg transition-colors duration-200"
                >
                  <div class="flex-shrink-0">
                    <div :class="[
                      'w-8 h-8 rounded-full flex items-center justify-center',
                      activity.type === 'registration' ? 'bg-blue-100 text-blue-600' :
                      activity.type === 'payment' ? 'bg-green-100 text-green-600' :
                      activity.type === 'dormitory' ? 'bg-purple-100 text-purple-600' :
                      'bg-gray-100 text-gray-600'
                    ]">
                      <component :is="activity.icon" class="h-4 w-4" />
                    </div>
                  </div>
                  <div class="flex-1 min-w-0">
                    <p class="text-sm text-gray-900">{{ activity.message }}</p>
                    <p class="text-xs text-gray-500">{{ formatRelativeTime(activity.time) }}</p>
                  </div>
                </div>
              </div>
            </Card>
          </div>
        </div>
      </main>
    </div>
  </Sidebar>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore, useAdminStore } from '../../stores'
import { formatDate, formatRelativeTime } from '../../utils'
import Sidebar from '../../components/common/Sidebar.vue'
import Header from '../../components/common/Header.vue'
import Card from '../../components/common/Card.vue'
import DashboardChart from '../../components/charts/DashboardChart.vue'
import {
  HomeIcon,
  UserGroupIcon,
  AcademicCapIcon,
  BuildingOfficeIcon,
  BuildingOffice2Icon,
  ClipboardDocumentCheckIcon,
  CurrencyDollarIcon,
  MegaphoneIcon,
  PlusIcon,
  DocumentArrowUpIcon,
  ChartBarIcon,
  BellIcon,
  CreditCardIcon,
  UserPlusIcon
} from '@heroicons/vue/24/outline'

const router = useRouter()
const authStore = useAuthStore()
const adminStore = useAdminStore()

// 菜单配置
const menuItems = [
  {
    name: '首页',
    path: '/admin/dashboard',
    icon: HomeIcon
  },
  {
    name: '学生管理',
    path: '/admin/students',
    icon: UserGroupIcon
  },
  {
    name: '专业管理',
    path: '/admin/majors',
    icon: AcademicCapIcon
  },
  {
    name: '班级管理',
    path: '/admin/classes',
    icon: BuildingOfficeIcon
  },
  {
    name: '宿舍管理',
    path: '/admin/dormitory',
    icon: BuildingOffice2Icon
  },
  {
    name: '报到管理',
    path: '/admin/registration',
    icon: ClipboardDocumentCheckIcon
  },
  {
    name: '财务管理',
    path: '/admin/finance',
    icon: CurrencyDollarIcon
  },
  {
    name: '通知公告',
    path: '/admin/notices',
    icon: MegaphoneIcon
  }
]

// 状态
const loading = ref(false)
const chartsLoading = ref(false)

// 当前日期
const currentDate = computed(() => {
  return formatDate(new Date(), 'YYYY年MM月DD日')
})

// 统计数据
const statistics = ref([
  {
    title: '总学生数',
    value: '1,200',
    change: '+12%',
    icon: UserGroupIcon,
    color: 'blue'
  },
  {
    title: '已报到',
    value: '980',
    change: '+8%',
    icon: ClipboardDocumentCheckIcon,
    color: 'green'
  },
  {
    title: '已缴费',
    value: '850',
    change: '+15%',
    icon: CurrencyDollarIcon,
    color: 'yellow'
  },
  {
    title: '入住率',
    value: '75%',
    change: '+5%',
    icon: BuildingOffice2Icon,
    color: 'purple'
  }
])

// 图表数据
const registrationTrendData = ref([
  { name: '8月1日', value: 120 },
  { name: '8月2日', value: 180 },
  { name: '8月3日', value: 250 },
  { name: '8月4日', value: 320 },
  { name: '8月5日', value: 480 },
  { name: '8月6日', value: 650 },
  { name: '8月7日', value: 850 }
])

const majorDistributionData = ref([
  { name: '计算机科学与技术', value: 320 },
  { name: '软件工程', value: 280 },
  { name: '数据科学与大数据技术', value: 250 },
  { name: '人工智能', value: 200 },
  { name: '网络工程', value: 150 }
])

const paymentProgressData = ref([
  { name: '学费', value: 85 },
  { name: '住宿费', value: 78 },
  { name: '教材费', value: 65 },
  { name: '保险费', value: 92 },
  { name: '体检费', value: 88 }
])

// 快捷操作
const quickActions = [
  {
    name: '新增学生',
    description: '添加新学生信息',
    icon: UserPlusIcon,
    path: '/admin/students'
  },
  {
    name: '批量导入',
    description: '批量导入学生数据',
    icon: DocumentArrowUpIcon,
    path: '/admin/students'
  },
  {
    name: '发布通知',
    description: '发布新的通知公告',
    icon: MegaphoneIcon,
    path: '/admin/notices'
  },
  {
    name: '财务报表',
    description: '查看财务统计报表',
    icon: ChartBarIcon,
    path: '/admin/finance'
  }
]

// 最新动态
const recentActivities = ref([
  {
    id: 1,
    type: 'registration',
    message: '张三完成了报到手续',
    time: new Date(Date.now() - 5 * 60 * 1000),
    icon: ClipboardDocumentCheckIcon
  },
  {
    id: 2,
    type: 'payment',
    message: '李四完成了学费缴纳',
    time: new Date(Date.now() - 15 * 60 * 1000),
    icon: CreditCardIcon
  },
  {
    id: 3,
    type: 'dormitory',
    message: '王五被分配到1号楼101宿舍',
    time: new Date(Date.now() - 30 * 60 * 1000),
    icon: BuildingOffice2Icon
  },
  {
    id: 4,
    type: 'notice',
    message: '发布了新的报到须知',
    time: new Date(Date.now() - 60 * 60 * 1000),
    icon: BellIcon
  }
])

// 统计卡片组件
const StatCard = ({ title, value, change, icon, color }) => {
  const colorClasses = {
    blue: 'bg-blue-500',
    green: 'bg-green-500',
    yellow: 'bg-yellow-500',
    purple: 'bg-purple-500',
    red: 'bg-red-500'
  }
  
  return {
    template: `
      <div class="card hover:shadow-lg transition-shadow duration-200">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <div class="w-8 h-8 rounded-md flex items-center justify-center text-white ${colorClasses[color]}">
              <component :is="icon" class="h-5 w-5" />
            </div>
          </div>
          <div class="ml-5 w-0 flex-1">
            <dl>
              <dt class="text-sm font-medium text-gray-500 truncate">{{ title }}</dt>
              <dd class="flex items-baseline">
                <div class="text-2xl font-semibold text-gray-900">{{ value }}</div>
                <div class="ml-2 flex items-baseline text-sm font-semibold text-green-600">
                  {{ change }}
                </div>
              </dd>
            </dl>
          </div>
        </div>
      </div>
    `,
    props: ['title', 'value', 'change', 'icon', 'color']
  }
}

// 处理快捷操作
const handleQuickAction = (path) => {
  router.push(path)
}

// 处理登出
const handleLogout = () => {
  authStore.logout()
  router.push('/admin/login')
}

// 处理个人资料
const handleProfileClick = () => {
  // 可以打开个人资料弹窗或跳转到个人资料页面
  console.log('Profile clicked')
}

// 处理设置
const handleSettingsClick = () => {
  // 可以打开设置弹窗或跳转到设置页面
  console.log('Settings clicked')
}

// 加载数据
const loadData = async () => {
  loading.value = true
  chartsLoading.value = true
  
  try {
    // 加载统计数据
    await adminStore.fetchStatistics()
    
    // 模拟加载延迟
    setTimeout(() => {
      chartsLoading.value = false
    }, 1000)
  } catch (error) {
    console.error('Failed to load dashboard data:', error)
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
/* 自定义样式 */
</style>